package com.qf.ithub.movie_demo01.service.impl;

import com.qf.ithub.movie_demo01.entity.Role;
import com.qf.ithub.movie_demo01.entity.RoleActionRight;
import com.qf.ithub.movie_demo01.entity.RoleActionRightExample;
import com.qf.ithub.movie_demo01.entity.RoleExample;
import com.qf.ithub.movie_demo01.entity.dto.ActionDTO;
import com.qf.ithub.movie_demo01.entity.dto.GrantDTO;
import com.qf.ithub.movie_demo01.mapper.ActionRightMapper;
import com.qf.ithub.movie_demo01.mapper.RoleActionRightMapper;
import com.qf.ithub.movie_demo01.mapper.RoleMapper;
import com.qf.ithub.movie_demo01.mapper.RoleRightMapper;
import com.qf.ithub.movie_demo01.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : xixi
 * @Title :
 * @date :  2021-03-19 15:29
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleRightMapper roleRightMapper;

    @Autowired
    private RoleActionRightMapper roleActionRightMapper;

    @Autowired
    private ActionRightMapper actionRightMapper;

    @Override
    public List<Role> getRole() {
        List<Role> roles = roleMapper.selectByExample(null);

        return roles;
    }

    @Override
    public void addRole(Role role) {
//        roleMapper.insertSelective(role);
         roleMapper.insert(role);
    }
    /**
     * 获得所有的动作权限
     * @return
     */
    public List<ActionDTO> selectAllActionRightByParentid(){
        //获取动作权限父节点
        List<ActionDTO> roots = actionRightMapper.selectAllActionRightByParentid(0);
        for (ActionDTO root : roots) {
            List<ActionDTO> actionDTOS = actionRightMapper.selectAllActionRightByParentid(root.getRightid());
            root.setChirdren(actionDTOS);
        }
        return  roots;
    }
    /**
     * 获取指定角色除父节点之外的所有动作权限
     */
    public  List<Integer> selectActionRightByRolNoParent(Integer roleid){
        return actionRightMapper.selectActionRightByRolNoParent(roleid);
    }
    /**
     * 给指定的其角色赋予菜单权限
     */
    @Transactional
    public void grantActionRight( GrantDTO grantDTO){
        //先删除指定的角色的所有的权限
        RoleActionRightExample roleActionRightExample=new RoleActionRightExample();
        roleActionRightExample.createCriteria().andRoleidEqualTo(grantDTO.getRoleid());
        roleActionRightMapper.deleteByExample(roleActionRightExample);
        //一条一条地插进去
        List<Integer> ids = grantDTO.getRights();
        for (int i=0;i<ids.size();i++) {
            RoleActionRight roleActionRight =new RoleActionRight();
            roleActionRight.setRoleid(grantDTO.getRoleid());
            roleActionRight.setRightid(ids.get(i));
            roleActionRightMapper.insertSelective(roleActionRight);
        }
    }

}
